package dbcp;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * DBCP 连接池
 * Created by kevin on 2020/3/26.
 */
public class Demo1 {
    private static Properties properties = null;
    static {
        try {
            InputStream in = Demo1.class.getClassLoader().getResourceAsStream("dbconfig.properties");
            properties = new Properties();
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void fun1(){
        /**
         * 1、创建连接池对象
         * 2、配置4大参数(驱动类,url,name,password)
         * 3、配置池参数
         * 4、得到连接对象
         */
        //1、创建连接池对象
        BasicDataSource basicDataSource = new BasicDataSource();
        //2、配置4大参数(驱动类,url,name,password)
        basicDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        basicDataSource.setUrl(properties.getProperty("url"));
        basicDataSource.setUsername(properties.getProperty("name"));
        basicDataSource.setPassword(properties.getProperty("password"));
        //3、配置连接池参数
        basicDataSource.setMaxTotal(20);
        basicDataSource.setMinIdle(3);
        basicDataSource.setMaxWaitMillis(1000);
        //4、得到连接池对象
        try {
            Connection connection = basicDataSource.getConnection();
            System.out.println(connection.getClass().getName());
            /**
             * 连接池内部是使用mysql驱动提供的Connection
             * 连接池使用mysql连接对象进行了装饰,只对close()方法进行了增强
             * 装饰之后的Connection的close()方法,用来把当前连接归还给池
             */
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
